package com.doubi.common.config.jwt;

import com.doubi.common.aspectj.annotation.Delay;
import com.doubi.common.aspectj.annotation.NeedLogin;
import com.doubi.common.config.expiry.ExpiryException;
import com.doubi.common.config.shiro.ShiroUtil;
import com.doubi.constants.SystemConstants;
import com.doubi.model.map.ExpiryMap;
import com.doubi.service.SysUserService;
import com.doubi.utils.DataUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUitl jwtUitl;
    @Autowired
    private SysUserService sysUserService;
    //有过期时间的map
    private static final ExpiryMap<String, String> ExpiryMap = new ExpiryMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查有没有需要用户权限的注解
        String UUID = null;
        if (method.isAnnotationPresent(NeedLogin.class)) {
            String token = getToken(request);// 从 http 请求头中取出 token
            if (StringUtils.isBlank(token)) {
                throw new JwtException("无token，请重新登录");
            }
            // 获取签名信息
            Claims claims = jwtUitl.getClaimByToken(token);
            // 判断签名是否存在或过期
            boolean b = claims == null || claims.isEmpty() || jwtUitl.isTokenExpired(claims.getExpiration());
            if (b) {
                throw new JwtException("token验证失败！,请重新登录");
            }
            // 将签名中获取的用户信息放入request中;
            UUID = claims.getSubject();
        } else {
            String token = getToken(request);// 从 http 请求头中取出 token
            if (!StringUtils.isBlank(token)) {
                // 获取签名信息
                Claims claims = jwtUitl.getClaimByToken(token);
                // 判断签名是否存在或过期
                boolean b = claims == null || claims.isEmpty() || jwtUitl.isTokenExpired(claims.getExpiration());
                if (!b) {
                    UUID = claims.getSubject();
                }
            }
        }
        //记录最后操作时间
        if(UUID != null){
            sysUserService.updateUserLastTime(UUID);
        }
        // 将签名中获取的用户信息放入request中;;
        request.setAttribute(SystemConstants.SESSION_KEY_USERINFO, UUID);
        //处理多次提交
        if (method.isAnnotationPresent(Delay.class)) {
            if (DataUtil.isEmpty(UUID)) {
                UUID = ShiroUtil.getIp();
            }
            UUID = request.getContextPath() + ":" + request.getServletPath() + ":" + UUID;
            Delay delay = method.getAnnotation(Delay.class);
            if (ExpiryMap.containsKey(UUID)) {
                throw new ExpiryException();
            } else {
                ExpiryMap.put(UUID, UUID, delay.time());
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

    /**
     * 获取请求Token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(jwtUitl.getHeader());
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUitl.getHeader());
        }
        return token;
    }
}
